import { mapMutations, mapActions, mapState } from "vuex";
import { typeClassName } from "@/pages/config/classNameMap";
import _ from "lodash";
import dayjs from "dayjs";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.camelCase(
      name
        .split("/")
        .pop()
        .replace(/\.\w+$/, "")
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  watch: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.watchs.map((item) => {
      this.$watch(item.target, item.fn, { deep: item.deep });
    });
    this.$nextTick(() => {
      this.unwatch = this.$watch("vms", (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      this.init();
      if (process.env.NODE_ENV === "development") {
        console.log({
          me: this,
          vms: this.vms,
          completeLoad: this.completeLoad,
        });
      }
    });
  },
  destroyed() {
    this.unwatch();
  },
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false,
      me: this,
      watchs: [],
      models: {
        //模型
        salesOrder: {
          ...typeClassName["salesOrder"],
        },
        productionPlan: {
          ...typeClassName["productionPlan"],
        },
        reductionRouting: {
          ...typeClassName["reductionRouting"],
        },
      },
      parentId: "",
      planParentId: "",
      workCenterParentId: "",
      mainStatus: "",
      mainApproveStatus: "",
      productOptions: [],
      locked: false,
      isAbled: false,
      refOrderBotTable: "orderBotTable",
      refOrderTopTable: "orderTopTable",
      dataSet: {
        //数据集
        orderNotBindTableData: [],
        orderBindTableData: [],
        leftCurrentIndex: null,
        leftTableData: [],
        leftTableCurrent: null,
        leftTableSelection: [],
        leftPlanTableSelection: [],
        leftProuductionId: "",
        leftFormData: {},
        planTopTableData: [],
        planBotTableData: [],
        planFormData: {},
        approvalFormData: {
          operateTime: "",
          action: "申请",
          status: "申请",
          opinions: "",
        },
        approvalRecords: [],
        needOrderTableData: [],
        needOrderFormData: {},
        workCenterTableData: [],
        workCenterSelections: [],
        approvalOrderData: [],
      },
      needIds: [],
      workCenterSelectItem: [],
      workCenterOtherItem: [],
      workCenterRoutingId: "",
      productId: "",
      planType: "碳化钨合批",
      onlyRead: false,
      leftFilter: {},
      rightFilter: {
        orderFrom: "&& orderFrom == '合批订单'",
        product: "碳化钨",
      },
    };
  },
  computed: {
    attrs() {
      return {
        labelWidth: 100,
        labelPosition: "right",
        cols: 3,
        columns: [
          {
            key: "planBatchNo",
            title: "计划批次号",
            minWidth: 100,
            align: "center",
            config: { type: "text" },
          },
          // {
          //   key: "planType",
          //   title: "计划类型",
          //   minWidth: 100,
          //   align: "center",
          //   config: { type: "text" },
          // },
          // {
          //   key: "productId",
          //   title: "产物ID",
          //   minWidth: 100,
          //   align: "center",
          //   config: { type: "select",options:this.productOptions },
          // },
          // {
          //   key: "status",
          //   title: "状态",
          //   minWidth: 100,
          //   align: "center",
          //   config: { type: "text" },
          // },
          // {
          //   key: "routingId",
          //   title: "工艺路径",
          //   minWidth: 100,
          //   align: "center",
          //   config: { type: "number" },
          // },
          {
            key: "planStartTime",
            title: "计划开始时间",
            minWidth: 200,
            align: "center",
            config: { type: "datetime" },
          },
          {
            key: "planEndTime",
            title: "计划结束时间",
            minWidth: 200,
            align: "center",
            config: { type: "datetime" },
          },
          {
            key: "startTime",
            title: "实际开始时间",
            minWidth: 200,
            align: "center",
            config: { type: "datetime" },
          },
          {
            key: "endTime",
            title: "实际结束时间",
            minWidth: 200,
            align: "center",
            config: { type: "datetime" },
          },
          {
            key: "totalCapacity",
            title: "计划产量",
            minWidth: 100,
            align: "center",
            config: { type: "number" },
          },
          {
            key: "usedCapacity",
            title: "已产量",
            minWidth: 100,
            align: "center",
            config: { type: "number" },
          },
          {
            key: "restCapacity",
            title: "剩余未产",
            minWidth: 100,
            align: "center",
            config: { type: "number" },
          },
          {
            key: "df_maxFSSS",
            title: "最大FSSS",
            minWidth: 100,
            align: "center",
            config: { type: "number" },
          },
          {
            key: "df_minFSSS",
            title: "最小FSSS",
            minWidth: 100,
            align: "center",
            config: { type: "number" },
          },
          {
            key: "df_maxCT",
            title: "最大CT",
            minWidth: 100,
            align: "center",
            config: { type: "number" },
          },
          {
            key: "df_minCT",
            title: "最小CT",
            minWidth: 100,
            align: "center",
            config: { type: "number" },
          },
          {
            key: "remark",
            title: "备注",
            minWidth: 100,
            align: "center",
            config: { type: "textarea" },
          },
        ],
        rules: {
          planBatchNo: [{ required: true, message: "请输入", trigger: "blur" }],
        },
      };
    },
  },
  methods: {
    init() {
      this.getProduct();
    },
    changeTabs(name) {
      console.log(name);
      this.tabName = name;
      if (name == 0) {
        this.orderBindLoadPage();
        this.orderNotBindTable(
          this.vms[this.refOrderBotTable].pageNavigation,
          {}
        );
      } else {
        this.planLoadPage();
      }
    },
    changePlanTabs(name) {
      console.log(name);
      this.planName = name;
      this.dataSet.planTopTableData = [];
      this.dataSet.planBotTableData = [];
      this.dataSet.orderNotBindTableData = [];
      this.dataSet.orderBindTableData = [];
      if (name == 0) {
        this.rightFilter.orderFrom = "&& orderFrom == '合批订单'";
        this.rightFilter.product = "碳化钨";
        this.planType = "碳化钨合批";
        this.refOrderBotTable = "orderBotTable";
        this.refOrderTopTable = "orderTopTable";
      } else if (name == 1) {
        this.rightFilter.orderFrom = "&& orderFrom == '合批订单'";
        this.rightFilter.product = "钨粉";
        this.planType = "钨粉合批";
        this.refOrderBotTable = "orderBotTable2";
        this.refOrderTopTable = "orderTopTable2";
      } else if (name == 2) {
        this.rightFilter.orderFrom = "&& orderFrom != '合批订单'";
        this.rightFilter.product = "碳化钨";
        this.planType = "碳化钨库存";
        this.refOrderBotTable = "orderBotTable3";
        this.refOrderTopTable = "orderTopTable3";
      } else if (name == 4) {
        this.rightFilter.orderFrom = "&& orderFrom != '合批订单'";
        this.rightFilter.product = "钨粉";
        this.planType = "钨粉库存";
        this.refOrderBotTable = "orderBotTable4";
        this.refOrderTopTable = "orderTopTable4";
      } else {
        this.rightFilter.orderFrom = "&& orderFrom != '合批订单'";
        this.rightFilter.product = "配碳";
        this.planType = "配碳库存";
        this.refOrderBotTable = "orderBotTable5";
        this.refOrderTopTable = "orderTopTable5";
      }
      this.vms.leftTable.pageNavigation.pageNumber = 1;
      this.leftLoadPage(this.vms.leftTable.pageNavigation, {});
    },
    /**
     * 逻辑操作：
     * 1. 获取左侧表格数据
     * 2. 点击左侧表格数据，右侧出现表格，并且勾选相关联的数据 leftTableClick
     * **/
    leftLoadPage(pageNavigation, filter) {
      let newFilter = {
        ...filter,
        className: this.models.productionPlan.className,
        type: this.models.productionPlan.type,
        planType: this.planType,
      };
      this._$queryByPage(
        this.models["productionPlan"].clzs,
        pageNavigation,
        newFilter,
        "",
        "updateTime",
        false
      ).then((res) => {
        this.dataSet.leftTableData =
          this.models["productionPlan"].clzs.valueRecords;
        this.vms.leftTable.pageNavigation.total = res.recordCount;
      });
    },
    /**
     *
     * @param {分页信息} pageNavigation
     * @param {筛选信息} filter
     * @param {*} orderBy
     * @returns
     * 获取右侧表格数据
     */
    orderNotBindTable(pageNavigation, filter) {
      filter = this._merge(filter, {
        className: this.models.salesOrder.className,
        type: this.models.salesOrder.type,
      });
      let data = {
        pageNumber: pageNavigation.pageNumber,
        pageSize: pageNavigation.pageSize,
        product: this.rightFilter.product,
        condition: this._$setFilteStr(filter) + this.rightFilter.orderFrom,
      };

      this.$api.production.querySalesOrderNotLinkByPage(data).then((res) => {
        console.log(res);
        this.dataSet.orderNotBindTableData = res.records.map((item) => {
          return {
            ...item,
            ...item.values,
          };
        });
        this.vms[this.refOrderBotTable].attrs.pageNavigation.total =
          res.recordCount;
      });
    },
    // 订单绑定
    orderBindLoadPage() {
      if (this.dataSet.leftCurrentIndex == null) {
        this.$Message.info("请选择左侧生产计划");
        return;
      }
      let linkId = this.dataSet.leftTableSelection.map((item) => {
        return item.link.linkId;
      });
      if (linkId.length == 0) {
        this.dataSet.orderBindTableData = [];
        this.productId = "";
        return;
      }
      this.models.salesOrder.clzs.queryByIds(linkId).then((res) => {
        this.dataSet.orderBindTableData =
          this.models["salesOrder"].clzs.valueRecords;
        this.planBindLoadPage();
        let tableData = this._clone(this.dataSet.orderBindTableData);
        this.productId = tableData[0].productId;
        // 判断左侧表格当前选中项是否有数据
        if (this.dataSet.leftTableCurrent) {
          // this.dataSet.leftTableCurrent = this.dataSet.leftTableData[this.dataSet.leftCurrentIndex]
          let ids = this.dataSet.leftTableCurrent.hier.content.map(
            (row) => row.link.linkId
          );
          tableData.forEach((item, index) => {
            // 初始化所有选中状态 为false
            item._checked = false;
            if (ids.includes(item.id)) {
              item._checked = true;
            }
          });
          this.dataSet.orderBindTableData = tableData;
        }
      });
    },
    //订单选择
    orderTopTableSelect(selection) {
      if (this.productId !== "") {
        let ifProduct = selection.every((item) => {
          return item.productId == this.productId;
        });
        if (!ifProduct) {
          this.$Message.info("请选择同一产品");
          return;
        }
      }

      let selIds = selection.map((item) => item.id);
      let dataArray = selIds.map((id) => {
        return {
          containerModel: this.models.productionPlan.modelType,
          containerId: this.dataSet.leftTableCurrent.id,
          parentId: this.parentId,
          linkId: id,
          values: { linkId: id },
        };
      });
      this.$api.production
        .addSalesOrderLinkToProductionPlan({ data: dataArray })
        .then((flag) => {
          this.leftUpdateData();
          this.leftLoadPage(this.vms.leftTable.pageNavigation, {});
        });
    },
    orderBotTableSelect(selection) {
      let selIds = selection.map((item) => item.id);
      let linkIds = this.dataSet.leftTableSelection.map((item) => {
        return item.link.linkId;
      });
      let ids = this._diff(selIds, linkIds);
      let delIdItems = this.dataSet.leftTableSelection.filter((item) =>
        ids.includes(item.link.linkId)
      );
      let delIds = delIdItems.map((item) => item.id);
      // let delIds = this.dataSet.leftTableCurrent.hier.content
      //   .filter((item) => selIds.includes(item.link.linkId))
      //   .map((item) => item.id);

      this.$api.production
        .deleteSalesOrderLinkToProductionPlan({
          linkIds: ids,
          ids: delIds,
          containerId: this.dataSet.leftTableCurrent.id,
        })
        .then((flag) => {
          this.leftUpdateData();
          this.leftLoadPage(this.vms.leftTable.pageNavigation, {});
        });
    },
    /**
     * 左侧更新数据
     * 注:右侧每次选中取消时,要及时更新左侧选中的数据
     */
    leftUpdateData() {
      this.models["productionPlan"].clz
        .queryById(this.dataSet.leftTableCurrent.id)
        .then((res) => {
          this.dataSet.leftTableCurrent =
            this.models["productionPlan"].clz.valueRecord;
          this.dataSet.leftProuductionId =
            this.dataSet.leftTableCurrent.productId;
          this.dataSet.leftTableData[this.dataSet.leftCurrentIndex] =
            this.models["productionPlan"].clz.valueRecord;
          this.dataSet.leftTableSelection =
            this.dataSet.leftTableCurrent.hier.content.filter(
              (item) => item.parentId == this.parentId
            );
          this.dataSet.leftPlanTableSelection =
            this.dataSet.leftTableCurrent.hier.content.filter(
              (item) => item.parentId == this.planParentId
            );
          if (this.planType.indexOf("合批") > -1) {
          }
          if (this.tabName == "生产订单") {
            this.orderNotBindTable(
              this.vms[this.refOrderBotTable].attrs.pageNavigation,
              {}
            );
            this.orderBindLoadPage();
          } else {
            this.planLoadPage();
          }
        });
    },
    getNeedOrderTable(ids) {
      this.models["salesOrder"].clzs.queryByIds(ids).then((res) => {
        this.dataSet.needOrderTableData =
          this.models["salesOrder"].clzs.valueRecords;
      });
    },
    /**
     *
     * @param {*} item
     * @param {*} index
     */
    leftClick(item, index) {
      // 存储左侧当前点击的数据
      let _data = this.dataSet.leftTableData[index];

      let status = _data.status;
      this.mainStatus = status;
      this.mainApproveStatus = _data.approveStatus;
      if (
        status != "创建" ||
        this.mainApproveStatus == "申请" ||
        this.mainApproveStatus == "再申请"
      ) {
        this.vms[this.refOrderBotTable].attrs.config.checkColumnDisabled = true;
        this.vms[this.refOrderTopTable].attrs.config.checkColumnDisabled = true;
        // this.vms.planTopTable.config.action = false;
        // this.vms.planTopTable.config.additionalAction = false;
      } else {
        this.vms[
          this.refOrderBotTable
        ].attrs.config.checkColumnDisabled = false;
        this.vms[
          this.refOrderTopTable
        ].attrs.config.checkColumnDisabled = false;
        // this.vms.planTopTable.config.action = true;
        // this.vms.planTopTable.config.additionalAction = true;
      }

      this.dataSet.leftCurrentIndex = index;
      this.dataSet.leftTableCurrent = _data;
      this.dataSet.leftProuductionId = this.dataSet.leftTableCurrent.productId;
      this.dataSet.leftTableSelection = [];
      this.dataSet.leftPlanTableSelection = [];
      this.parentId = this._$getHierItemField(_data.hier, "订单", "nodeId");
      this.planParentId = this._$getHierItemField(
        _data.hier,
        "子计划",
        "nodeId"
      );
      if (this.planType.indexOf("合批") > -1 || this.planType == "碳化钨库存") {
        this.needOrderParentId = this._$getHierItemField(
          _data.hier,
          "需求",
          "nodeId"
        );
        let needOrderTableData =
          this.dataSet.leftTableCurrent.hier.content.filter(
            (item) => item.parentId == this.needOrderParentId
          );
        this.needIds = needOrderTableData.map((item) => item.link.linkId);
        this.getNeedOrderTable(this.needIds);
      }

      this.dataSet.leftTableSelection =
        this.dataSet.leftTableCurrent.hier.content.filter(
          (item) => item.parentId == this.parentId
        );
      this.dataSet.leftPlanTableSelection =
        this.dataSet.leftTableCurrent.hier.content.filter(
          (item) => item.parentId == this.planParentId
        );
      // 初始化右侧表格分页获取数据

      if (this.tabName == "生产订单") {
        this.orderNotBindTable(
          this.vms[this.refOrderBotTable].attrs.pageNavigation,
          {}
        );
        this.orderBindLoadPage();
      } else {
        this.planLoadPage();
        this.planBindLoadPage();
      }
    },

    toDoExecute(row) {
      let data = {
        id: row.id,
        status: "锁定",
      };
      this.$api.production.updateProductionPlanStatus(data).then((res) => {
        this.$Message.success("锁定成功");
        this.leftLoadPage(this.vms.leftTable.pageNavigation, {});
      });
    },

    /**
     * 新增巡检计划
     */
    leftTableCreate() {
      this._setVmValue("createModal", "config.show", true);
      // this.vms.createModal.show = true;
      this.onlyRead = false;
      // 整理数据格式
      this.dataSet.leftFormData = this.$modelObject.getTpl(
        this.models.productionPlan.modelType
      );
    },
    /**
     * 查看巡检计划
     * @param {*} row 行数据
     * @param {*} index
     */
    leftTableDetail(row, index) {
      this.dataSet.leftFormData = row;
      // this.vms.detailModal.show = true;
      this._modalShow("detailModal");
      this.onlyRead = true;
    },
    /**
     * 编辑巡检计划
     * @param {*} row 行数据
     * @param {*} index 索引
     */
    leftTableEdit(row, index) {
      this.dataSet.leftFormData = row;
      this._modalShow("editModal");
      this.onlyRead = false;
    },

    /**
     * @param {*} row 行数据
     * @param {*} index 索引
     */
    leftTableDelete(row, index) {
      let _this = this;
      this._$deleteConfirm(() => {
        _this
          ._$deleteByIds(_this.models["productionPlan"].clzs, [row.id])
          .then((res) => {
            this.leftLoadPage(
              _this.vms.leftTable.pageNavigation,
              {},
              "",
              "",
              false
            );
          });
      });
    },
    /**
     * 巡检计划多选删除
     * @param {*} row 行数据
     */
    leftTableDeleteMultiple(row) {
      let _this = this;
      this._$deleteConfirm(() => {
        let ids = row.map((items) => String(items.id));
        _this
          ._$deleteByIds({
            ids: ids,
          })
          .then((res) => {
            _this.leftLoadPage(
              _this.vms.leftTable.pageNavigation,
              {},
              "",
              "",
              false
            );
          });
      });
    },

    // 创建巡检项提交
    createModalOk(btn) {
      this.vms.createView.validate((valid) => {
        if (valid) {
          this.dataSet.leftFormData.values.planType = this.planType;
          this._merge(this.dataSet.leftFormData, {
            className: this.models.productionPlan.className,
            type: this.models.productionPlan.type,
          });
          this.$api.production
            .addProductionPlan(this.dataSet.leftFormData)
            .then((res) => {
              this._modalClose("createModal");
              btn.loading = false;
              this.vms.leftTable.pageNavigation.pageNumber = 1;
              this.leftLoadPage(this.vms.leftTable.pageNavigation, {});
            });
        } else {
          btn.loading = false;
          this._$requireInfo();
        }
      });
    },
    /**
     * 编辑巡检计划提交
     */
    editModalOk(btn) {
      this.vms.editView.validate((valid) => {
        if (valid) {
          this.models.productionPlan.clz.setRecord(this.dataSet.leftFormData);
          this.models.productionPlan.clz.updateById().then((flag) => {
            if (flag) {
              this._modalClose("editModal");
              this.leftLoadPage(
                this.vms.leftTable.pageNavigation,
                {},
                "",
                "",
                false
              );
            }
            btn.loading = false;
          });
        } else {
          btn.loading = false;
          this._$requireInfo();
        }
      });
    },

    planLoadPage() {
      let linkId = this.dataSet.leftPlanTableSelection.map((item) => {
        return item.link.linkId;
      });
      if (linkId.length == 0) {
        this.dataSet.planTopTableData = [];
        return;
      }
      this.models.reductionRouting.clzs.queryByIds(linkId).then((res) => {
        this.dataSet.planTopTableData =
          this.models["reductionRouting"].clzs.valueRecords;
      });
    },
    planBindLoadPage() {
      this.dataSet.planBotTableData =
        this.models["salesOrder"].clzs.valueRecords;
    },
    planSelect(selection) {
      let leftIds = this.dataSet.leftPlanTableSelection.map(
        (item) => item.link.linkId
      );
      let selIds = selection.map((item) => item.id);
      let delLinkIds = leftIds.filter((id) => !selIds.includes(id));
      let addLinkIds = selIds.filter((id) => !leftIds.includes(id));

      if (delLinkIds.length > 0) {
        let delIds = this.dataSet.leftTableCurrent.hier.content
          .filter((item) => delLinkIds.includes(item.link.linkId))
          .map((item) => item.id);

        this.$api.HierInstanceDeleteHier(delIds).then((flag) => {
          this.leftUpdateData();
        });
      }
      if (addLinkIds.length > 0) {
        let dataArray = addLinkIds.map((id) => {
          let item = selection.find((item) => item.id == id).values;
          return {
            containerModel: this.models.productionPlan.modelType,
            containerId: this.dataSet.leftTableCurrent.id,
            parentId: this.planParentId,
            linkId: id,
            values: {
              linkId: id,
              sf_code: item.sf_code,
              sf_name: item.sf_name,
              if_equ: item.if_equ,
            },
          };
        });
        this.$api.HierInstanceSaveHier(dataArray).then((flag) => {
          this.leftUpdateData();
        });
      }
    },
    planTableCreate() {
      if (this.dataSet.leftCurrentIndex == null) {
        this.$Message.info("请先选择左侧子计划");
        return;
      }
      if (
        this.dataSet.leftProuductionId == null ||
        this.dataSet.leftProuductionId == ""
      ) {
        this.$Message.info("请先绑定生产订单");
        return;
      }
      if (
        this.mainStatus != "创建" ||
        this.mainApproveStatus == "申请" ||
        this.mainApproveStatus == "再申请"
      ) {
        this.$Message.info("该状态下不能新增");
        return;
      }
      // if (this.mainStatus == "创建") {
      //   this.$Message.info("主计划创建状态,不可创建");
      //   return;
      // }
      this._modalShow("createPlanModal");
      this.onlyRead = false;
      // 整理数据格式
      this.dataSet.planFormData = this.$modelObject.getTpl(
        this.models.reductionRouting.modelType
      );
      this.dataSet.planFormData.values.productId =
        this.dataSet.leftProuductionId;
      this.dataSet.planFormData.values.planType = this.planType;
    },
    planTableEdit(row, index) {
      if (row.status !== "启用") {
        this.$Message.error("已经执行过了，不能修改");
        return;
      }
      if (this.mainStatus != "创建") {
        this.$Message.info("主计划创建状态,不可编辑");
        return;
      }

      this.vms.editPlanModal.show = true;
      this.dataSet.planFormData = row;
    },
    planTableDetail(row) {
      this._modalShow("detailPlanModal");
      this.dataSet.planFormData = row;
    },

    // 创建提交
    createPlanModalOk(btn) {
      this.vms.createPlanModal.loading = true;
      this.vms.createPlanView.validate((valid) => {
        if (valid) {
          let newData = {
            values: this.dataSet.planFormData.values,
            container: {
              containerClassName: this.models.productionPlan.className,
              containerType: this.models.productionPlan.className,
              containerModel: this.models.productionPlan.modelType,
              containerId: this.models.productionPlan.clzs.valueRecords[0].id,
              parentId: this.planParentId,
            },
          };

          this.$api.production.addRouting(newData).then((res) => {
            this._modalClose("createPlanModal");
            btn.loading = false;
            this.leftUpdateData();
          });
        }
        btn.loading = false;
      });
    },

    editPlanModalOk(btn) {
      this.vms.editPlanModal.loading = true;
      this.vms.editPlanView.validate((valid) => {
        if (valid) {
          this.models.reductionRouting.clz.setRecord(this.dataSet.planFormData);
          this.models.reductionRouting.clz.updateById().then((res) => {
            this._modalClose("editPlanModal");
            this.leftUpdateData();
          });
          btn.loading = false;
        }
        this.vms.editPlanModal.loading = false;
        btn.loading = false;
      });
    },

    planTableDelete(row, index) {
      if (this.mainStatus == "启用") {
        this.$Message.info("主计划非创建状态,不可删除");
        return;
      }
      if (row.status == "创建") {
        this.$api.production.deletePlan(row).then((res) => {
          this.leftUpdateData();
        });
      } else {
        this.$Message.error("只有创建状态可以删除");
        return;
      }
    },
    handleApprovalModal(row) {
      this.vms.approvalModal.show = true;
      if (row.approveStatus == null) {
        this.dataSet.approvalFormData.action = "申请";
        this.dataSet.approvalFormData.status = "申请";
      } else {
        this.dataSet.approvalFormData.action = "再申请";
        this.dataSet.approvalFormData.status = "再申请";
      }
      let now = dayjs().format("YYYY-MM-DD 00:00:00");
      this.dataSet.approvalFormData["operatorId"] = this.G_Account.userId;
      this.dataSet.approvalFormData["operatorName"] =
        "admin" || this.G_Account.userName;
      this.dataSet.approvalFormData["id"] = row.id;
      this.dataSet.approvalFormData["operateTime"] = now;
      this.getRecords(row);
    },
    getRecords(data) {
      let parentId = this._$getHierItemField(data.hier, "审批", "nodeId");
      this.dataSet.approvalRecords = data.hier.content.filter(
        (item) => item.parentId == parentId
      );
      this.$api.production.queryProductionPlanAndHier(data).then((res) => {
        console.log(res);
        let orderParentId = this._$getHierItemField(res.hier, "订单", "nodeId");
        this.dataSet.approvalOrderData = res.hier.content
          .filter((item) => item.parentId == orderParentId)
          .map((item) => {
            return {
              ...item,
              ...item.values,
            };
          });
        let sonPlanParentId = this._$getHierItemField(
          res.hier,
          "子计划",
          "nodeId"
        );

        this.dataSet.sonPlanTableData = res.hier.content
          .filter((item) => item.parentId == sonPlanParentId)
          .map((item) => {
            return {
              ...item,
              ...item.values,
            };
          });
      });
    },
    approvelModalOk() {
      this.vms.approvalModal.loading = true;
      let data = this.dataSet.approvalFormData;
      let formData = {
        pointer: {
          className: this.models.productionPlan.className,
          type: this.models.productionPlan.type,
          id: data.id,
        },
        approveValues: {
          operatorId: data.operatorId,
          operatorName: data.operatorName,
          operateTime: data.operateTime,
          action: data.action,
          status: data.status,
          opinions: data.opinions,
        },
      };

      this.$api.production.approveProductionPlan(formData).then((res) => {
        console.log(res);
        this.vms.approvalModal.loading = false;
        this.vms.approvalModal.show = false;
        this.leftLoadPage(this.vms.leftTable.pageNavigation, {});
      });
    },
    handleNeedEdit(row) {
      console.log(row);
      this._modalShow("needModal");
      this.dataSet.needOrderFormData = this.$modelObject.getTpl(
        this.models.salesOrder.modelType
      );
      this.dataSet.needOrderFormData.values = row;
    },
    handleNeedDetail(row) {
      this.dataSet.needOrderFormData = this.$modelObject.getTpl(
        this.models.salesOrder.modelType
      );
      this._modalShow("needDetailModal");
      this.dataSet.needOrderFormData.values = row;
    },
    editNeedModalOk(btn) {
      this.vms.needView.validate((valid) => {
        if (valid) {
          this._merge(this.dataSet.needOrderFormData, {
            className: this.models.salesOrder.className,
            id: this.dataSet.needOrderFormData.values.id,
            type: this.models.salesOrder.type,
            name: this.dataSet.needOrderFormData.values.name,
          });
          this.$api.production
            .updateRequireSalesOrder(this.dataSet.needOrderFormData)
            .then((res) => {
              this._modalClose("needModal");
              btn.loading = false;
              this.leftUpdateData();
            });
          btn.loading = false;
        }
        btn.loading = false;
      });
    },
    planTableExecution(row, index) {
      if (row.status !== "启用") {
        this.$Message.error("已经执行过了，不能重复执行");
        return;
      }

      this.$api.production.toDoExecutePlan(row).then((res) => {
        this.planLoadPage();
      });
    },
    selectWorkCenter(row, index) {
      this.workCenterRoutingId = row.id;
      // this.workCenterParentId = this._$getHierItemField(
      //   row.hier,
      //   "workCenter",
      //   "nodeId"
      // );
      let tableData = row.hier.content
        .filter((item) => item.name == "workCenter")
        .map((item) => {
          return {
            ...item,
            ...item.values,
          };
        });
      tableData.forEach((item) => {
        if (item.link.linkId != null) {
          item._checked = true;
        }
      });
      this.dataSet.workCenterTableData = tableData;
      this._modalShow("workCenterModal");
    },
    workCenterTableSelect(selection) {
      this.dataSet.workCenterSelections = selection;
      // this.workCenterOtherItem =
      // workCenterSelectItem:[],
      // workCenterOtherItem:[],
    },
    editWorkCenterModalOk(btn) {
      let newSelectItem = this.dataSet.workCenterSelections.filter(
        (item) => item.link.linkId == null
      );
      this.workCenterSelectItem = newSelectItem.map(
        (item) => item.workCenterName
      );
      let otherSelectItem = this.dataSet.workCenterTableData.filter(
        (item) =>
          !this.dataSet.workCenterSelections
            .map((ele) => ele.workCenterName)
            .includes(item.workCenterName)
      );
      let delSelectItem = otherSelectItem.filter(
        (item) => item.link.linkId != null
      );
      this.workCenterOtherItem = delSelectItem.map((item) => item.link.linkId);
      let data = {
        routingId: this.workCenterRoutingId,
        initWorkCenterNames: this.workCenterSelectItem,
        delWorkCenterIds: this.workCenterOtherItem,
      };
      this.$api.production.dealRoutingWorkCenter(data).then((res) => {
        this.$Message.success("操作成功");
        this._modalClose("workCenterModal");
        btn.loading = false;
        this.leftUpdateData();
      });
    },
    getProduct() {
      let data = {
        type: "material",
        className: "MaterialDetail",
      };
      this.$api.ResourceInstance.query(data)
        .then((res) => {
          console.log(res);
          // this.dataSet.routing = res.data.data.records;
          this._$getOptions(res, "productOptions");
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
